package com.woniuxy.interceptor;


import com.woniuxy.annotations.RequireRole;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

@Component
public class AuthRoleInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            if(method.isAnnotationPresent(RequireRole.class)){
                RequireRole requireRole=method.getDeclaredAnnotation(RequireRole.class);
                String[] roles=requireRole.role();
                for(String role:roles){
                    if(role.equals(request.getHeader("role"))){
                        return true;
                    }
                }
            }else{
                return true;
            }
        }else{
            return true;
        }
        response.setStatus(400);
        return false;
    }
}
